import React, {useState, useEffect} from 'react';
import {useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import {
  Text,
  Image,
  View,
  StyleSheet,
  SafeAreaView,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import {homeApi, Home} from '../../../api';
import {NavBar} from '@fruits-chain/react-native-xiaoshu';
import {p} from '../../../utils/pxToDp';

export default () => {
  const navigation = useNavigation<StackNavigationProp<any>>();
  useEffect(() => {
    getAllArticleList();
  }, []);

  const [articleList, setArticleList] = useState<Home.AllArticleInfo[]>();

  const getAllArticleList = async () => {
    const res = await homeApi.getAllArticleListApi({
      page: 1,
      page_size: 10,
    });
    console.log('1', res.data.list);
    setArticleList(res.data.list);
  };

  const renderItem = ({item}: {item: Home.AllArticleInfo}) => {
    const styles = StyleSheet.create({
      contentLayout: {
        flex: 1,
        flexDirection: 'row',
        marginTop: 14,
      },
      articleImage: {
        width: 100,
        height: 100,
        marginRight: 10,
        borderRadius: 10,
      },
      rightLayout: {
        justifyContent: 'center',
        flex: 1,
      },
      articleTitle: {
        marginBottom: 8,
        color: '#000',
        fontSize: 18,
        fontWeight: 'bold',
      },
      articleInfo: {
        color: '#666',
        fontSize: 14,
      },
    });
    return (
      <TouchableOpacity
        style={styles.contentLayout}
        onPress={() => {
          navigation.push('ArticleInfo', {id: item.id});
        }}>
        <Image
          style={styles.articleImage}
          source={{uri: item.article_image}}></Image>

        <View style={styles.rightLayout}>
          <Text style={styles.articleTitle}>{item.article_title}</Text>
          <Text style={styles.articleInfo} numberOfLines={2}>
            {item.article_info}
          </Text>
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <SafeAreaView style={{backgroundColor: '#fff'}}>
      <NavBar
        backArrowColor="#666"
        leftExtra={<Text style={styles.navBarLeftText}>文章列表</Text>}
        onPressBackArrow={() => {
          navigation.goBack();
        }}
      />
      <FlatList
        data={articleList}
        renderItem={renderItem}
        contentContainerStyle={{marginHorizontal: 20}}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  navBarLeftText: {
    fontSize: p(14),
    color: '#666',
  },
});
